'use strict'

const Koa = require('koa')
const router = require('koa-router')()
const bodyparser = require('koa-bodyparser')
const cors = require('koa-cors')
const {Sequelize,Op} = require('sequelize')

const Blog = require('./model/Blog')

const sequelize = new Sequelize('demo04','postgres','Zou2001827.',{
    host:'zbmwd.top',
    dialect:'postgres'
})

sequelize.authenticate().then(()=>{
    try {
        console.log('连接成功')
    } catch (error) {
        console.log('连接失败')
    }
})

let blogs = sequelize.define('blog',Blog)
// sequelize.sync({force:true}).then(()=>{
//     blogs.bulkCreate([
//         {
//             title:'.net修养',
//             zhaoyao:'无',
//             neirong:'这是',
//             fenlei:'.net',
//             zuozhe:'老i',
//         },
//         {
//             title:'java修养',
//             zhaoyao:'无',
//             neirong:'这是',
//             fenlei:'java',
//             zuozhe:'老t',
//         },
//     ])
// })


const app = new Koa()

app.use(cors())
app.use(bodyparser())

router.get('/blog',async(ctx,next)=>{
    let keyword = ctx.request.query.keyword
    let list
    if(keyword){
        list = await blogs.findAll({
            where:{
                [Op.or]:[
                    {id:isNaN(keyword)?0:parseInt(keyword)},
                    {title:keyword},
                    {zhaoyao:keyword},
                    {neirong:keyword},
                    {fenlei :keyword},
                    {zuozhe:keyword}
                ]
            },
            order:['id']
        })
        ctx.body={
            code:10001,
            data:list,
            msg:'请求成功'
        }
    }else{
        list = await blogs.findAll({
            order:['id']
        })
        ctx.body={
            code:10001,
            data:list,
            msg:'请求成功'
        }
    }
})
router.get('/blog/:id',async(ctx,next)=>{
    let id = ctx.request.params.id
    let list = await blogs.findByPk(id)
    ctx.body={
        code:20001,
        data:list,
        msg:'查找成功'
    }
})
router.post('/blog',async(ctx,next)=>{
    let obj = ctx.request.body
    console.log(obj);
    let list = await blogs.create(obj)
    ctx.body={
        code:30001,
        data:list,
        msg:'添加成功'
    }
})
router.put('/blog/:id',async(ctx,next)=>{
    let id = ctx.request.params.id
    let obj = ctx.request.body

    let list = await blogs.update(obj,{
        where:{
            id:id
        }
    })
    ctx.body={
        code:40001,
        data:list,
        msg:'修改成功'
    }
    
})
router.delete('/blog/:id',async(ctx,next)=>{
    let id = ctx.request.params.id
    console.log(id);
    await blogs.destroy({
        where:{
            id:id
        }
    })
    ctx.body={
        code:40001,
        data:{id},
        msg:'删除成功'
    }
})

app.use(router.routes())

app.listen(3000,()=>{
    console.log(`http://localhost:3000`);
})